package com.wl.thread.demo05;

/**
 * 不安全的买票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"王磊").start();
        new Thread(station,"瞌睡王").start();
        new Thread(station,"火神").start();

    }
}

class BuyTicket implements Runnable{

    private int ticketNums = 10;
    //外部停止
    boolean flag = true;

    @Override
    public void run() {
        while(flag){
            try {
                buy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized 同步方法 锁的是this
    private synchronized void buy() throws InterruptedException {
        if (ticketNums <=  0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}
